#-*-coding:utf-8-*-
'''
@ info: gmail manage!
@ date: 2012-09-06
@ author: huangzy
'''
import urllib  
import urllib2 
import sys, httplib, os,check
from django.conf import settings
from crm.models import Members
from crm.models import Agent
from crm.models import gMaillog
from crm.models import gMailList
from crm.models import gMailLetter
from crm.models import Projects
from models import Salesperson,Role
from models import Salesperson_groups
from django.shortcuts import get_object_or_404,render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django import forms
from django.core.paginator import Paginator, InvalidPage
import grap_mail_api as grap
from datetime import datetime
import logClass as log

log = log.Log()

def sendmail(request):
    '''发送邮件页面和处理ajax发送邮件'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    if request.is_ajax():
        maillistid = request.POST.get('maillistid','')
        gmid = request.POST.get('gmid','')
        lettername = request.POST.get('lettername','')
        object = request.POST.get('object','')
        mailcon = request.POST.get('mailcon','')
        host = request.POST.get('host','')

        letid = request.POST.get('letid','')
        logid = request.POST.get('logid','')
        newletterid = request.POST.get('newletterid','')
        
        
        #return HttpResponse('''{"code":0,"info":"%s"}'''%mailcon)
        this_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S');
        this_name = datetime.now().strftime('%Y%m%d%H%M%S')

        error_code = 0
        error_info = """'Function':'%s','Info':'%s'"""
        ids = ''

        mail_sendid = 0
        mail_send = 0
        ''' crm_gmailletter benin'''
        lettername = lettername
        if lettername=='':
            lettername = this_name
        
        '''将邮件信息保存到gmailletter本地数据库中'''
        '''
        from django.db import connection, transaction 
        cursor=connection.cursor()
        sql = """insert into `crm_gmailletter` (`lettername`,`lettercon`,`addtime`,`adduser`) values('%s','%s','%s','%s')"""%(lettername,mailcon,this_time,request.session['name'])
        try:
            ret = cursor.execute(sql)
            transaction.commit_unless_managed()  
        except Exception,e:
            log.error('【%s】 - 【%s】'%(`sql`,e))
        '''
        if letid:
            letter_id = letid
            newletterid = newletterid
        else:
            if maillistid=='' or gmid=='' or object=='' or mailcon=='&nbsp;' or host=='':
                return HttpResponse('''{"code":0,"info":"Parameter Error"}''')
            try:
                newletter=gMailLetter(
                    lettername = lettername,
                    lettercon = mailcon,
                    addtime = this_time,
                    adduser = request.session['name']
                )
                newletter.save()
                newletter = gMailLetter.objects.order_by('addtime')
                newletter = gMailLetter.objects.filter(addtime=this_time)
                for a in newletter:
                    letter_id = a.id
            except Exception,e:
                log.error('【%s】'%(e))
                return HttpResponse('''{"code":0,"info":"%s"}'''%e)

        if  logid:
            mailid = logid
        else:
            try:
                '''将邮件信息保存到gMaillog本地数据库中'''
                maillog=gMaillog(
                    maillist_id = maillistid,
                    gmaillist_id = gmid,
                    gletter_id = letter_id,
                    mail_object = object,
                    mail_sendtime = this_time,
                    mail_senduser = request.session['name']
                )
                maillog.save()
                newmail = gMaillog.objects.order_by('mail_sendtime')
                newmail = gMaillog.objects.filter(mail_sendtime=this_time)
                for a in newmail:
                    mailid = a.id
            except Exception,e:
                log.error('【%s】'%(e))
                return HttpResponse('''{"code":0,"info":"%s"}'''%e)
        
        emailUrl = '''http://%s/gmailinfo/?mlid=%s'''%(host,mailid)
        #emailUrl = '''http://www.stanford.edu.hk/dm/feedm2.html'''
        #emailUrl = '''http://www.chinaedugrp.com/dm/hvedm.html'''
        if not newletterid:
            new_letter = grap.post_import_newsletter('%s'%emailUrl,'New','%s'%lettername)
            mail_letterid = 0
            if(new_letter['code']=='1'):
                letter_import = 1
                mail_letterid = new_letter['info']
            else:
                letter_import = 2
                error_info = error_info%('post_import_newsletter',new_letter['info'])
            newletterid = mail_letterid
        else:
            letter_import = 1
            mail_letterid = newletterid

        ids = '%s,%s,%s'%(letter_id,mailid,newletterid)
        if letter_import==1:
            sendmail = grap.post_sendmail(maillistid,mail_letterid,object.encode('gbk'))
            if sendmail['code']=='1':
                mail_send = 1
                mail_sendid = sendmail['info']
                error_code = 1
                error_info = error_info%('post_sendmail','Mail sent successfully')
            else:
                mail_send = 2
                error_info = error_info%('post_sendmail',sendmail['info'].decode('utf8'))
        
        try:
            upmaillog=gMaillog.objects.get(pk=mailid)
            upmaillog.letterid=mail_letterid
            upmaillog.mail_sendtime=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            upmaillog.mail_issend=mail_send
            upmaillog.mail_sendid=mail_sendid
            upmaillog.save()
        except Exception,e:
            log.error('【%s】 - 【%s】'%(`upmaillog`,e))
        
        from django.db import connection, transaction 
        cursor=connection.cursor()
        sql = """update `crm_gmailletter` set `letterid`='%s',`htmlurl`='%s',letter_import='%s' where `id`='%s'"""%(mail_letterid,emailUrl,letter_import,letter_id)
        try:
            cursor.execute(sql)
            transaction.commit_unless_managed() 
        except Exception,e:
            log.error('【%s】 - 【%s】'%(`sql`,e))
        cursor.close()
        return HttpResponse('''{"code":%s,"info":"%s","ids":"%s"}'''%(error_code,error_info,ids))
    
    return render_to_response('grapmail/sendmail.html')

def create_maillist(request):
    '''创建邮件联系人组'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    if request.is_ajax():
        maillist = request.POST.get('maillist','')
        listname = request.POST.get('listname','')
        host = request.POST.get('host','')
        listid = request.POST.get('listid','')
        
        oldlist = gMailList.objects.filter(is_removed__lt =1,maillist_id__gt=0,maillist_name=listname).order_by('id')

        if len(oldlist)>0:
            return HttpResponse('''{"code":0,"info":"List Name already exists!"}''')
        del(oldlist)
        this_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S');
        this_name = datetime.now().strftime('%Y%m%d%H%M%S')
        
        if listname=='':
            listname = this_time

        error_code = 0
        error_info = "Function:%s,Info:%s"
        maillist_id = 0
        mailfile_path = 0
        mail_import = 0

        maillists = maillist[1:].split(',')
        if listid:
            oldlist = gMailList.objects.filter(pk=int(listid))
            for a in oldlist:
                mailfile_path = a.mailfile_path
            #mailfile_path = oldlist['mailfile_path']
            fileUrl = 'http://%s/%s'%(host,mailfile_path)
            del(oldlist)
        else:
            mailfile_path = 'static/mailfile/maillist/%s.txt'%(this_name)
            fileUrl = 'http://%s/%s'%(host,mailfile_path)
            '''生成email文件地址供api使用'''
            try:
                mailfile = open(mailfile_path,'a+')
                for a in maillists:
                    mailfile.write('%s\n'%a)
            finally:
                mailfile.close()
        fileUrl = 'http://www.ceacbj.com.cn/www/51094/for_harvard.txt'
        createMail = grap.post_create_mailinglist(listname)
        if createMail and createMail['code']=='1':
            maillist_id = createMail['info'];
            importMail = grap.post_import_mailinglist(fileUrl,maillist_id)
            if importMail and importMail['code']=='1':
                mail_import = 1
                error_code = 1
            else:
                mail_import = 2
                error_info = error_info%('post_import_mailinglist',importMail['info'])
        else:
            error_info = error_info%('post_create_mailinglist',createMail['info'])
        
        if listid:
            oldlist = gMailList.objects.get(pk=int(listid))
            oldlist.maillist_id = maillist_id
            oldlist.mail_import = mail_import
            oldlist.save()
        else:
            try:
                maillist=gMailList(
                    maillist_id = maillist_id,
                    maillist_name = listname,
                    mailfile_path = mailfile_path,
                    mail_import = mail_import,
                    mail_addtime = this_time,
                    mail_senduser = request.session['name'],
                )
                maillist.save()
                newmail = gMailList.objects.filter(mail_addtime = this_time).order_by('id')
                for a in newmail:
                    listid = a.id
            except Exception,e:
                log.error('【%s】 - 【%s】'%(`maillist`,e))
            
        if error_code == 1:
            error_info = error_info%('suc',maillist_id)
            
        return HttpResponse('''{"code":%s,"info":"%s","ids":"%s"}'''%(error_code,error_info,listid))
    return HttpResponse('''Can't Access!''')

def gmaillist(request):
    '''邮件联系人组列表'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    
    if request.method == 'GET':
        page=int(request.GET.get('page',1))
        pagesize = int(request.GET.get('ps',10))
        is_con = int(request.GET.get('is_con',0))
        listname = request.GET.get('listname','')
        adduser = request.GET.get('adduser','')

        limit = '%s,%s'%((page-1)*pagesize,pagesize)

        where = ''
        
        if listname:
            where += """ and `maillist_name` like '%%%%%s%%%%' """%listname
        
        if adduser:
            where += """ and `mail_senduser` like '%%%%%s%%%%' """%adduser

        from django.db import connection
        cursor=connection.cursor()
        sql = """select * from `crm_gmaillist` where `maillist_id`>0 and `mail_import`>0 and `is_removed`=0 %s order by `mail_addtime` desc limit %s"""%(where,limit)
        sql1 = """select count(*) as num from `crm_gmaillist` where  `id` in(select id from `crm_gmaillist` where `maillist_id`>0 and `mail_import`>0 and `is_removed`=0 %s) """%where
        cursor.execute(sql)
        maillist = cursor.fetchall()
        cursor.execute(sql1)
        tol = cursor.fetchall()
        #totalnum = tol[0]['num']
        #tolpage = int(totalnum/pagesize)+1
        cursor.close();
        if len(tol)>0:
            tolpage = int(int(tol[0][0])/pagesize)
            if int(tol[0][0])%pagesize !=0:
                tolpage = tolpage+1
        else:
            tolpage = 1

    return render_to_response('grapmail/gmaillist.html',{
        'page':page,
        'pagesize':pagesize,
        'tolpage':tolpage,
        'maillists':maillist,
        'is_con':is_con,
        'listname':listname,
        'adduser':adduser,
        'ttt':''
    })

def matchmail(request):
    '''发送历史邮件查询'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    
    page=int(request.GET.get('page',1))
    pagesize = int(request.GET.get('ps',15))
    is_con = int(request.GET.get('is_con',0))
    
    where = ''
    limit = '%s,%s'%((page-1)*pagesize,pagesize)
    from django.db import connection
    cursor=connection.cursor()
    sql = '''select log.*,list.mailfile_path,list.maillist_name from `crm_gmaillog` log left join  `crm_gmaillist` list on list.id=log.gmaillist_id  where log.`is_removed`<1 and log.`letterid`>0 %s order by log.`mail_sendtime` desc limit %s'''%(where,limit)
    sql1 = '''select count(1) from `crm_gmaillog` where `id` in(SELECT `id` FROM `crm_gmaillog` WHERE `is_removed`<1 and `letterid`>0 %s)'''%where
    cursor.execute(sql)
    mails = cursor.fetchall()
    cursor.execute(sql1)
    tol = cursor.fetchall()
    if len(tol)>0:
        tolpage = int(int(tol[0][0])/pagesize)
        if int(tol[0][0])%pagesize !=0:
            tolpage = tolpage+1
    else:
        tolpage = 1
    
    return render_to_response('grapmail/matchmail.html',{'tolpage':tolpage,'page':page,'ps':pagesize,'is_con':is_con,'mails':mails,'ttt':''})

def gmailinfo(request):
    '''邮件具体内容展示'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    mlid=int(request.GET.get('mlid',0))
    if not mlid:
        return render_to_response('error/404.shtml')
    
    maillog = gMaillog.objects.get(pk=mlid)
    try:
        lettercon = gMailLetter.objects.get(pk=maillog.gletter_id)
        content = lettercon.lettercon.tostring()
    except Exception,e:
        content = 'Content is empty!'
    
    #return HttpResponse('''<html><head></head><body>%s</body></html>'''%lettercon.lettercon.tostring());
    return render_to_response('grapmail/gmailinfo.html',{'mail':maillog,'mailcon':content,'ttt':''})

def selectuser(request):
    '''用户邮件地址查询'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    agent_list = Agent.objects.order_by('id')
    project_list = Projects.objects.order_by('id')
    
    if request.method == 'GET':
        from django.db.models import Q
        page=int(request.GET.get('page',1))
        pagesize = int(request.GET.get('ps',10))
        p_id=request.GET.get('p_id',0)
        is_con = int(request.GET.get('is_con',0))
        a_id=request.GET.get('a_id',0)
        sales=request.GET.get('sales')
        
        where = ''

        if int(p_id) !=0:
            where = 'and `projects_id`=%s'%p_id
        if int(a_id) !=0:
            where = 'and `agent_id`=%s'%a_id
        
        limit = '%s,%s'%((page-1)*pagesize,pagesize)
    

        from django.db import connection
        cursor=connection.cursor()
        cursor1=connection.cursor()
        sql = '''select name,email from `crm_members` where 1=1 %s group by `email` limit %s'''%(where,limit)
        sql1 = '''select count(1) from `crm_members` where id in(SELECT id FROM `crm_members` WHERE 1 =1 %s GROUP BY `email`)'''%where
        cursor.execute(sql)
        members = cursor.fetchall()
        cursor1.execute(sql1)
        tol = cursor1.fetchall()
        #totalnum = tol[0]['num']
        #tolpage = int(totalnum/pagesize)+1
        
        if len(tol)>0:
            tolpage = int(int(tol[0][0])/pagesize)
            if int(tol[0][0])%pagesize !=0:
                tolpage = tolpage+1
        else:
            tolpage = 1
        
        '''
        members = Members.objects.filter(is_removed=0).distinct()
        if sales:
            salesup=sales.capitalize()
            members=members.filter(Q(salesperson__name__icontains=sales)|Q(salesperson__name__icontains=salesup))
        if int(p_id) !=0:
            members=members.filter(projects__pk=int(p_id))
        if int(a_id) !=0:
            members=members.filter(agent__pk=int(a_id))
        
        totalnum = len(members)
        tolpage = int(totalnum/pagesize)+1
        members = members.order_by('-id')[(page-1)*pagesize:page*pagesize]
        '''
    return render_to_response('grapmail/selectmail.html',{
        'project_list':project_list,
        'agent_list':agent_list,
        'sales':sales,
        'a_id':a_id,
        'p_id':p_id,
        'is_con':is_con,
        'members':members,
        'tolpage':tolpage,
        'pagesize':pagesize,
        'page':page,
        'ttt':''
    })

def delgmaillist(request):
    '''邮件列表删除功能'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    if request.is_ajax():
        gmid = int(request.POST.get('gmid',0))
        mlistid = int(request.POST.get('mlistid',0))
        filename = request.POST.get('filename',0)
        filepath = '%s/%s'%(settings.WEB_ROOT,filename)
        try:
            os.remove(filepath)
        except:
            pass
        retcode = 0
        retinfo = ''
        
        if gmid==0 or mlistid==0:
            return HttpResponse('{"code":0,"info":"Parameters can\'t for empty"}')
        try:
            delret = grap.post_delete_mailinglist(mlistid)
            if delret['code']=='1':
                try:
                    upmaillist = gMailList.objects.get(pk=gmid)
                    upmaillist.is_removed = 1
                    upmaillist.save()
                    
                except:
                    gMailList.objects.get(pk=gmid).delete()
                retcode = 1
                retinfo = 'Successful operation'
            else:
                retcode = 0
                retinfo = delret['info']
        except Exception,e:
            retcode = 0
            retinfo = e
            log.error(e)
        return HttpResponse('{"code":%s,"info":"%s"}'%(retcode,retinfo))
    
    return render_to_response('error/404.shtml') 

def importgmaillist(request):
    '''邮件列表重新导入功能'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    '''重新导入邮件列表'''
    if request.is_ajax():
        gmid = int(request.POST.get('gmid',0))
        mlistid = int(request.POST.get('mlistid',0))
        filename = request.POST.get('filename',0)
        host = request.POST.get('host','')
        fileUrl = 'http://%s/%s'%(host,filename)
        fileUrl = 'http://www.ceacbj.com.cn/www/soap/20120910234225.txt'
        retcode = 0
        retinfo = ''
        
        if gmid==0 or mlistid==0 or filename==0:
            return HttpResponse('{"code":0,"info":"Parameters can\'t for empty"}')
        try:
            importret = grap.post_import_mailinglist(fileUrl,mlistid)
            if importret['code']=='1':
                try:
                    upmaillist = gMailList.objects.get(pk=gmid)
                    upmaillist.mail_import = 1
                    upmaillist.save()
                    retcode = 1
                    retinfo = 'Successful operation'
                except Exception,e:
                    log.error('【%s】 - 【%s】'%(`upmaillist`,e))
                    retcode = 0
                    retinfo = 'Database Error!'
            else:
                retcode = 0
                retinfo = importret['info']
        except Exception,e:
            retcode = 0
            retinfo = e
            log.error(e)
        return HttpResponse('{"code":%s,"info":"%s"}'%(retcode,retinfo))
    
    return render_to_response('error/404.shtml') 


def gletterlist(request):
    '''邮件列表重新导入功能'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    
    '''快讯列表'''
    page=int(request.GET.get('page',1))
    pagesize = int(request.GET.get('ps',10))
    is_con = int(request.GET.get('is_con',0))
    
    
    limit = '%s,%s'%((page-1)*pagesize,pagesize)
    from django.db import connection
    cursor=connection.cursor()
    sql = '''select * from `crm_gmailletter` where `is_removed`<1 and `letter_import`=1 order by `addtime` desc limit %s'''%(limit)
    sql1 = '''select count(1) from `crm_gmailletter` where `id` in(SELECT `id` FROM `crm_gmaillog` where `is_removed`<1 and `letter_import`=1)'''
    cursor.execute(sql)
    letters = cursor.fetchall()
    cursor.execute(sql1)
    tol = cursor.fetchall()
    cursor.close();
    if len(tol)>0:
        tolpage = int(int(tol[0][0])/pagesize)
        if int(tol[0][0])%pagesize !=0:
            tolpage = tolpage+1
    else:
        tolpage = 1

    return render_to_response('grapmail/gletterlist.html',{
        'is_con':is_con,
        'tolpage':tolpage,
        'pagesize':pagesize,
        'page':page,
        'letters':letters,
        'ttt':''
    })
